// LOF: low frequency oscillator
const ctx = new AudioContext();

const audioElement = document.createElement("audio");
audioElement.src = "audio/piano.mp3";
audioElement.setAttribute("controls", "controls");
audioElement.setAttribute("style", "display:block;margin: 200px auto;");
document.body.appendChild(audioElement);

const inputElement = document.createElement("input");
inputElement.type = "range";
inputElement.min = 0;
inputElement.max = 20; // LOF:0.01hz to 20hz
inputElement.value = 10;
inputElement.step = 0.01;
inputElement.setAttribute(
  "style",
  "display:block;width: 80%;margin: 100px auto;"
);
document.body.appendChild(inputElement);

const sourceNode = ctx.createMediaElementSource(audioElement);
const gainNode = ctx.createGain();
const oscNode = ctx.createOscillator();
oscNode.type = "sine";
oscNode.frequency.value = 10;
oscNode.start();

sourceNode.connect(gainNode);
// connect the oscillator to the gain node's gain property
oscNode.connect(gainNode.gain);
gainNode.connect(ctx.destination);

audioElement.addEventListener("start", async () => {
  if (ctx.state === "suspended") {
    await ctx.resume().catch(console.error);
  }
  oscNode.start(ctx.currentTime);
});

inputElement.addEventListener("input", (e) => {
  oscNode.frequency.value = +e.target.value;
});
